import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnInit, ViewChild } from '@angular/core';
import { STComponent, STColumn, STChange, STRequestOptions, STData } from '@delon/abc/st';
import { ACLService } from '@delon/acl';
import { SFComponent, SFSchema } from '@delon/form';
import { NzModalService } from 'ng-zorro-antd/modal';
import { SystemService } from '../../services/system.service';
import { CartConfigActionModalComponent } from './cart-config-action-modal/cart-config-action-modal.component';

@Component({
  selector: 'app-cart-config',
  templateUrl: './cart-config.component.html',
  styleUrls: ['./cart-config.component.less'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class CartConfigComponent implements OnInit {
  @ViewChild('st', { static: true })
  st!: STComponent;
  @ViewChild('sf', { static: false })
  sf!: SFComponent;
  tabs = [
    {
      name: '车型配置',
      type: 1,
      isActived: false,
      isShow: true
    },
    {
      name: '车长配置',
      type: 2,
      isActived: false,
      isShow: true
    },
    {
      name: '禁限物品名单',
      type: 3,
      isActived: false,
      isShow: true
    }
  ];
  tabType = 1;

  searchSchema: SFSchema = {
    properties: {
      tabType: {
        type: 'number',
        ui: {
          hidden: true
        }
      },
      params1: {
        title: '车型',
        type: 'string',
        ui: {
          placeholder: '请输入',
          visibleIf: {
            tabType: (value: number) => this.tabType === 1
          }
        }
      },
      params2: {
        title: '车长',
        type: 'string',
        ui: {
          placeholder: '请输入',
          visibleIf: {
            tabType: (value: number) => this.tabType === 2
          }
        }
      },
      params3: {
        title: '物品名称',
        type: 'string',
        ui: {
          placeholder: '请输入',
          visibleIf: {
            tabType: (value: number) => this.tabType === 3
          }
        }
      }
    }
  };

  columns: STColumn[] = [
    {
      title: '序号',
      className: 'text-center',
      width: 40,
      format: (item: STData, col: STColumn, idx: number) => {
        return ((this.st.pi -1) * this.st.ps) + idx + 1 + ''
      } 
    },
    { title: '车型',  width: 100, index: 'itemValue', iif: () => this.tabType === 1 },
    { title: '车长',  width: 100, index: 'itemValue', iif: () => this.tabType === 2 },
    { title: '物品名称',  width: 150, index: 'name', iif: () => this.tabType === 3 },
    {
      title: '启用状态',
      className: 'text-center',
      iif: () => this.tabType !== 3,
      index: 'statePaused',
      type: 'badge',
      width: 60,
      badge: {
        false: { text: '启用', color: 'success' },
        true: { text: '禁用', color: 'error' }
      }
    },
    {
      width: 150,
      title: '创建时间',
      index: 'modifyTime',
      type: 'date'
    },
    {
      width: 60,
      title: '操作',
      className: 'text-center',
      buttons: [
        {
          text: '编辑',
          acl: { ability: ['SYSTEM-CART-CONFIG-edit'] },
          click: item => this.configAction(item)
        },
        {
          text: '删除',
          acl: { ability: ['SYSTEM-CART-CONFIG-delete'] },
          click: item => this.deleteAction(item)
        }
      ]
    }
  ];

  loading = true;
  constructor(
    public service: SystemService,
    private nzModalService: NzModalService,
    private cdr: ChangeDetectorRef,
    private acl: ACLService
  ) {
    const acls = acl.data.abilities || [];
    this.tabs = [
      {
        name: '车型配置',
        type: 1,
        isActived: false,
        isShow: acl.data.full || !!acls.find(acl => acl === 'SYSTEM-CART-CONFIG-modeList')
      },
      {
        name: '车长配置',
        type: 2,
        isActived: false,
        isShow: acl.data.full || !!acls.find(acl => acl === 'SYSTEM-CART-CONFIG-cartLength')
      },
      {
        name: '禁限物品名单',
        type: 3,
        isActived: false,
        isShow: acl.data.full || !!acls.find(acl => acl === 'SYSTEM-CART-CONFIG-goodsList')
      }
    ];
    this.tabType = this.tabs.find(tab => tab.isShow)?.type || 1;
  }

  ngOnInit(): void {}

  beforeReq = (requestOptions: STRequestOptions) => {
    let params = {};
    switch (this.tabType) {
      case 1:
        Object.assign(params, { dictKey: 'car:model', itemValue: this.sf?.value.params1 });
        break;
      case 2:
        Object.assign(params, { dictKey: 'car:length', itemValue: this.sf?.value.params2 });
        break;
      case 3:
        Object.assign(params, { configFullKey: 'ban.goods.name', name: this.sf?.value.params3 });
        break;

      default:
        break;
    }
    Object.assign(requestOptions.body, params);
    this.loading = true;
    return requestOptions;
  };

  afterRes = (data: any[], rawData?: any) => {
    this.loading = false;
    return data;
  };

  // 切换Tab
  changeTab(item: any) {
    this.tabType = item.type;
    this.sf?.setValue('/tabType', item.type);
    this.sf?.reset();
    // this.tabs.forEach(i => (i.isActived = false));
    // item.isActived = !item.isActived;
    this.st.load(1);
    this.st.resetColumns();
    // this.cdr.detectChanges();
  }

  configAction(item?: any) {
    const modal = this.nzModalService.create({
      nzContent: CartConfigActionModalComponent,
      nzComponentParams: item
        ? { i: { ...item, itemValue: item.name }, configType: this.tabType }
        : { i: { id: 0 }, configType: this.tabType },
      nzFooter: null
    });
    modal.afterClose.subscribe(res => {
      if (res) {
        this.st.load();
        this.cdr.detectChanges();
      }
    });
  }

  deleteAction(item?: any) {
    this.nzModalService.error({
      nzTitle: '确认删除？',
      nzClosable: false,
      nzCancelText: '取消',
      nzOnOk: () => {
        this.service
          .request(this.tabType === 3 ? this.service.$api_remove_config_item : this.service.$api_delete_dict_by_ids, [item.id])
          .subscribe(res => {
            if (res) {
              this.service.msgSrv.success('删除配置成功');
              this.st.load(1);
            }
          });
      }
    });
  }
  /**
   * 重置表单
   */
  resetSF() {
    this.sf.reset();
  }
}
